/**
 * 
 */
package org.arpit.masteringextjs.dao.impl;

import java.util.List;

import org.arpit.masteringextjs.dao.CityDAO;
import org.arpit.masteringextjs.dao.DBUtility;
import org.arpit.masteringextjs.domain.Category;
import org.arpit.masteringextjs.domain.City;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

/**
 * @author arpit
 *
 */
public class CityDAOImpl implements CityDAO{

	private static CityDAO actorDAO;
	private SessionFactory sessionFactory = DBUtility.getSessionFactory();
	private CityDAOImpl () {
		
	}
	
	public static CityDAO getInstance() {
		if(actorDAO == null) {
			actorDAO = new CityDAOImpl();
		}
		return actorDAO;
	}
	
	@Override
	public List<City> findAll() {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(City.class);
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<City> actors = crit.list();
		session.getTransaction().commit();
		session.close();
		return actors;
	}

	@Override
	public City create(City actor) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		City createdActor = (City) session.merge(actor);
		session.getTransaction().commit();
		session.close();
		return createdActor;
	}

	@Override
	public City update(City city) {
		if(city.getId() == null || city.getId() == 0) {
			throw new IllegalArgumentException("Invalid data");
		}
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		City updatedCity = (City) session.merge(city);
		session.getTransaction().commit();
		session.close();
		return updatedCity;
	}

	@Override
	public void delete(long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(City.class);
		crit.add(Restrictions.eq("id", id));
		List<City> cities = crit.list();
		if(cities.isEmpty()) {
			throw new IllegalArgumentException("City with id " + id +" not found");
		}
		City city = cities.get(0);
		session.delete(city);
		session.getTransaction().commit();
		session.close();
	}

}
